package model

import (
	"gorm.io/gorm/clause"
)

type Module struct {
	Id string `xml:"id,attr" json:"id" gorm:"column:id;primary_key;not null;index;unique"`
	//Id string `xml:"id,attr" json:"id"`
	Name string `xml:"name,attr" json:"name" gorm:"not null;index"`
	Catagory string `xml:"catagory,attr" json:"catagory" gorm:"index"`
	Protocol string `xml:"protocol,attr" json:"protocol"`
	Sync_cycle *int `xml:"sync_cycle,attr" json:"sync_cycle" gorm:"column:sync_cycle;default:1000"`
	Timeout *int `xml:"timeout,attr" json:"timeout" gorm:"default:5000"`
	Enable *int `xml:"enable,attr" json:"enable" gorm:"default:1"`
	Host string `xml:"host,attr" json:"host" gorm:"not null"`
}
func FindModules(filter *Module)[]Module{
	var modules []Module
	if err:=sqldb.Find(&modules,filter).Error;err != nil{
		return nil
	}else{
		return modules
	}
}
func DeleteModules()(int64,error){
	var mods []Module
	sqldb.Find(&mods)
	index :=0
	for i:=0; i < len(mods); i++{
		if _,err := mods[i].Delete();err != nil{
			return int64(index),err
		}
		index += 1
	}
	return int64(index),nil
}
func (p* Module) Insert()error{
	return sqldb.Create(p).Error
}
func (p* Module) Save()(int64,error){
	var items []Item
	if err:=sqldb.Find(&items,&Item{Id:p.Id}).Error;err != nil{

	}else{
		for i:=0; i < len(items); i++{
			items[i].Tag = p.Catagory + ":" + p.Name
		}

		ret :=sqldb.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "id"},{Name:"code"}},
			DoUpdates: clause.AssignmentColumns([]string{"key", "tag", "name", "type", "convert", "kfac","offs","unit","direction","savetype","saveperiodmin","saveperiodmax","savedead","decimalpoints","mineu","maxeu"}),
		}).Create(&items)
		if ret.Error != nil{
			ret.Rollback()
		}
	}
	ret := sqldb.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns([]string{"name", "catagory", "protocol", "sync_cycle", "timeout", "enable","host"}),
	}).Updates(p)
	return ret.RowsAffected,ret.Error
}
func (p* Module) Delete()(int64,error){
	sqldb.Where(&Item{Id:p.Id}).Delete(&Item{})
	db :=sqldb.Where(&Module{Id:p.Id}).Delete(&Module{})
	return db.RowsAffected,db.Error
}
